package com.yys.apm.service;

import com.yys.apm.boot.ApmAgentManager;
import com.yys.apm.boot.spi.ServiceSPI;
import com.yys.apm.config.ApmConfig;
import com.yys.apm.logger.ILogger;
import com.yys.apm.logger.LoggerManager;
import com.yys.apm.utils.ApmAgentUtil;
import com.yys.apm.utils.OSUtil;

import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 应用系统信息上报服务
 *
 * @author Yingsheng Ye
 * @date 2021-03-23 09:47
 */
@ServiceSPI
public class OsInfoReportService implements ApmService {

    private static final ILogger logger = LoggerManager.getLogger(OsInfoReportService.class);


    private ScheduledExecutorService taskExecutor;

    private static String CLIENT_URL;

    private static String SECRET_KEY;

    @Override
    public void prepare() {
        ApmAgentManager agentManager = ApmAgentManager.getInstance();
        CLIENT_URL = agentManager.properties.getProperty(ApmConfig.PUSH_CLIENT_URL);
        SECRET_KEY = agentManager.properties.getProperty(ApmConfig.PUSH_SECRET_KEY);
        this.taskExecutor = Executors.newSingleThreadScheduledExecutor(r -> {
            Thread thread = new Thread(r, "os-report-task");
            thread.setDaemon(true);
            return thread;
        });
    }

    @Override
    public void startup() {
        this.taskExecutor.scheduleWithFixedDelay(() -> {
            Map<String, String> map = OSUtil.buildOSInfo();
            String data = ApmAgentUtil.objectToJson(map);
            logger.info("JVM信息上报:%s", data);
            ApmAgentUtil.sendHttpRequest(CLIENT_URL, ApmAgentUtil.buildRequestPkg(ApmAgentUtil.objectToJson(map), "osInfoReportService", SECRET_KEY));
        }, 0, 10, TimeUnit.MINUTES);
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void shutdown() {
        this.taskExecutor.shutdown();
    }
}
